package com.tipcp.equip.collect.service.strategy;

import com.digitalpetri.modbus.master.ModbusTcpMaster;
import com.digitalpetri.modbus.master.ModbusTcpMasterConfig;
import com.digitalpetri.modbus.requests.ReadHoldingRegistersRequest;
import com.digitalpetri.modbus.responses.ReadHoldingRegistersResponse;
import com.tipcp.equip.collect.constant.ModbusConstant;
import com.tipcp.equip.collect.domain.Equip;
import com.tipcp.equip.collect.domain.EquipEsModel;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Slf4j
@Component
public class TemperatureReadStrategy implements ReadTCPStrategy {
    public EquipEsModel readEquip(Object... args) {
        Equip equip = (Equip) args[1];
        ModbusTcpMasterConfig config = new ModbusTcpMasterConfig.Builder(equip.getIp()).setPort(equip.getPort()).build();
        ModbusTcpMaster master = new ModbusTcpMaster(config);
        EquipEsModel equipEsModel = new EquipEsModel();
        // 从寄存器读取温度等数据
        master.connect();
        CompletableFuture<ReadHoldingRegistersResponse> future =
                master.sendRequest(new ReadHoldingRegistersRequest(ModbusConstant.DEFAULT_START_ADDRESS, ModbusConstant.READ_TWO_REGISTER), ModbusConstant.SLAVE_ID);
        try {
            //TODO 后续定制解析格式
            float value = future.get().getRegisters().readFloat();
            equipEsModel.setEquipName(equip.getEquipName());
            equipEsModel.setEquipNum(equip.getEquipNum());
            equipEsModel.setId(UUID.randomUUID().toString());
            equipEsModel.setTemperature(value);
            equipEsModel.setCollectTime(new Date());
            ReferenceCountUtil.release(future.get());

        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        master.disconnect();
        return Objects.nonNull(equipEsModel.getId()) ? equipEsModel : null;
    }
}